package com.xi.service.Impl;

import com.xi.mapper.FineMapper;
import com.xi.mapper.UserMapper;
import com.xi.pojo.*;
import com.xi.service.FineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FineServiceImpl implements FineService {

    @Autowired
    private FineMapper fineMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void calculateAndApplyFine(Borrow borrow) {
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(borrow.getReturnTime())) {
            long daysLate = Duration.between(borrow.getReturnTime(), now).toDays();

            // 获取系统配置的逾期费用
            SystemConfig systemConfig = fineMapper.getSystemConfig(); // 新增方法获取配置
            double overdueFeePerDay = systemConfig != null ? systemConfig.getOverdueFees() : 2.0;

            double fineAmount = daysLate * overdueFeePerDay;

            Fine existingFine = fineMapper.getFineByBorrowId(borrow.getId());
            if (existingFine == null) {
                Fine newFine = new Fine();
                newFine.setUserId(borrow.getUserId());
                newFine.setBorrowId(borrow.getId());
                newFine.setFineAmount(fineAmount);
                newFine.setDueDate(now.toLocalDate());
                fineMapper.addFine(newFine);
            } else {
                existingFine.setFineAmount(fineAmount);
                existingFine.setDueDate(now.toLocalDate());
                fineMapper.updateFine(existingFine);
            }
        }
    }


    @Override
    public Double getTotalFinesByUserId(Integer userId) {
        List<Fine> fines = fineMapper.getFinesByUserId(userId);
        return fines.stream()
                .mapToDouble(Fine::getFineAmount)
                .sum();
    }

}
